<template>
  <view class="main">
    <view class="title">{{ petData.id ? '编辑资料' : '添加资料'}}</view>
    <view class="form_div">
      <view class="forms-item">
        <view class="label">宠物名 <text class="must">（必填）</text></view>
        <input v-model="petData.name" style="text-align: right;color:#414141;width:160px" placeholder="请填写（最多8字）" maxlength="8" />
      </view>
      <view class="forms-item">
        <view class="label">性别 <text class="must">（必填）</text></view>
        <view style="display:flex;align-items: center;">
          <image class="nocheck-image"
            :src="petData.sex == '1' ? 'https://img.qumoyugo.com/webimgbg/picopino_icon_sex_sure_match.png' : 'https://img.qumoyugo.com/webimgbg/picopino_icon_sex_no_match.png'"
            @click="checkSex('1')"></image>女
          <image class="nocheck-image" style="margin-left:40rpx"
            :src="petData.sex == '0' ? 'https://img.qumoyugo.com/webimgbg/picopino_icon_sex_sure_match.png' : 'https://img.qumoyugo.com/webimgbg/picopino_icon_sex_no_match.png'"
            @click="checkSex('0')"></image>男
        </view>
      </view>
      <view class="forms-item">
        <view class="label">生日 <text class="must" v-if="petConfig.birthdayEnable">（必填）</text></view>
        <view style="display:flex" :style="{color: petData.birthday ? '#414141' : '#999'}" @click="operatePopup">
          {{petData.birthday || '请选择'}}
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <view class="forms-item">
        <view class="label">品种 <text class="must" v-if="petConfig.breedEnable">（必填）</text></view>
          <input v-model="petData.breed" style="text-align: right;color:#414141;width:160px" placeholder="请填写（最多8字）" maxlength="8" />
      </view>
    </view>
    <view class="bottom_div">
      <view class="delete-btn u-center" v-if="petData.id" @click="dialogToggle">
        <image src="https://img.qumoyugo.com/img/TKA3BBHIVEMTGD4Q8BVFP1701400016358.svg" style="width: 36rpx;height: 36rpx;"></image>
      </view>
      <button class="submitOrder" @click="submit">{{ petData.id ? '确认修改' : '确认新增'}}</button>
    </view>
    <TipPlain ref="alertPopup" type="dialog">
      <view class="popup-tip-box">
        <view style="font-weight: bold;font-size:34rpx">确定要删除吗？</view>
        <view @click="dialogConfirm" class="btn">确认删除</view>
      </view>
    </TipPlain>
    <uni-popup ref="popupBirthday" background-color="#fff" type="bottom">
      <view>
        <view class="ope-title">
          <view class="box" @click="popupBirthdayClose()">取消</view>
          <view class="box" @click="sureBirthday">确定</view>
        </view>
        <picker-view style="padding: 0 80rpx; height: 300px;text-align: center;" :value="birthdayData.currentDate" @change="confirmCalendar">
          <picker-view-column>
            <view v-for="year in birthdayData.yearsList" :key="year" style="line-height: 30px">{{year}}年</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="month in birthdayData.monthsList" :key="month" style="line-height: 30px">{{month}}月</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="day in birthdayData.daysList" :key="day" style="line-height: 30px">{{day}}日</view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>
<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { getCurrentInstance, ref } from 'vue'
import TipPlain from '@/components/popup/plain'
import { ADD_PETS_CATEGORY } from '@/assets/js/config'
import { storage } from '@/utils/utils'
const date = new Date()
const years = []
const months = []
const days = []
for (let i = 2010; i <= date.getFullYear(); i++) {
  years.push(i)
}
for (let i = 1; i <= 12; i++) {
  months.push(i)
}
for (let i = 1; i <= 31; i++) {
  days.push(i)
}
const { $https } = getCurrentInstance().appContext.config.globalProperties
const petData = ref({
  id: null,
  name: null,
  breed: null,
  sex: '1',
  birthday: null
})
const birthdayData = ref({
  year: date.getFullYear(),
  month: new Date().getMonth() + 1,
  day: new Date().getDate(),
  currentDate: [9999, new Date().getMonth(), new Date().getDate() - 1], // 当前日期
  yearsList: years,
  monthsList: months,
  daysList: days
})
const petConfig = ref({})
const popupBirthday = ref(null)
onLoad(options => {
  if (options.pId) {
    $https({
      url: '/app/petManage/' + options.pId,
      type: ''
    }).then(res => {
      if (res.code === 0) {
        petData.value = res.data
      }
    })
  }
  if (options.eventsId) {
    getInt(options.eventsId)
  }
})
onShow(() => {
  const breedInfo = storage.get(ADD_PETS_CATEGORY) // 品种
  if (breedInfo) {
    petData.value.breed = breedInfo.breedName
    storage.remove(ADD_PETS_CATEGORY)
  }
})
const checkSex = (type) => {
  petData.value.sex = type
}
const alertPopup = ref(null)
const dialogToggle = () => {
  alertPopup.value.show()
}
const dialogConfirm = () => {
  del()
  alertPopup.value.close()
}
const operatePopup = () => {
  popupBirthday.value.open()
}
const popupBirthdayClose = () => {
  popupBirthday.value.close()
}
//
const confirmCalendar = e => {
  birthdayData.value.year = birthdayData.value.yearsList[e.detail.value[0]]
  birthdayData.value.month = birthdayData.value.monthsList[e.detail.value[1]]
  birthdayData.value.day = birthdayData.value.daysList[e.detail.value[2]]
}
const sureBirthday = () => {
  petData.value.birthday = `${birthdayData.value.year}-${birthdayData.value.month < 10 ? '0' + birthdayData.value.month : birthdayData.value.month}-${birthdayData.value.day < 10 ? '0' + birthdayData.value.day : birthdayData.value.day}`
  popupBirthdayClose()
}
// 保存提交
const submit = () => {
  if (!petData.value.name) {
    uni.showToast({ title: '请完善必填信息', icon: 'none' })
    return false
  }
  if (!petData.value.breed && petConfig.value.breedEnable) {
    uni.showToast({ title: '请完善必填信息', icon: 'none' })
    return false
  }
  if (!petData.value.sex) {
    uni.showToast({ title: '请完善必填信息', icon: 'none' })
    return false
  }
  if (!petData.value.birthday && petConfig.value.birthdayEnable) {
    uni.showToast({ title: '请完善必填信息', icon: 'none' })
    return false
  }
  $https({
    url: '/app/petManage/insertOrUpdate',
    type: '',
    method: 'post',
    data: petData.value
  })
    .then(res => {
      if (res.code === 0) {
        uni.showToast({ title: '操作成功', icon: 'none' })
        setTimeout(() => {
          uni.navigateBack({ delta: 1 })
        }, 1000)
      }
    })
    .catch(e => console.log(e))
}
const del = () => {
  if (!petData.value.id) {
    uni.showToast({
      title: '删除失败',
      icon: 'none'
    })
  } else {
    $https({
      url: '/app/petManage/' + petData.value.id,
      type: '',
      method: 'delete'
    }).then(res => {
      if (res.code === 0) {
        uni.showToast({
          title: '操作成功',
          icon: 'none',
          success: () => {
            uni.navigateBack({ delta: 1 })
          }
        })
      }
    }).catch(e => console.log(e))
  }
}
// 获取活动数据
const getInt = (id) => {
  $https({
    url: '/app/eventsInfo/enroll/' + id,
    type: '',
    method: 'get'
  }).then(res => {
    if (res.code === 0) {
      petConfig.value = res.data.petConfig || {}
    }
  })
}
</script>

<style scoped lang="scss">
@import "@/assets/styles/minx.scss";
.main {
  min-height: 100vh;
  padding: 30rpx 40rpx;
  .title{
    color: #000;
    font-size: 28rpx;
    font-weight: bold;
    line-height: 28rpx;
    margin-bottom: 20rpx;
  }
}
.form_div{
  .forms-item{
    position: relative;
    padding: 36rpx 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    &::before{
      @include border(top, #E1E1E1)
    }
    .must{
      color: #F0831E;
    }
    .label{
      color: #737373;
    }
  }
}

.bottom_div {
  width: 100%;
  position: fixed;
  bottom: env(safe-area-inset-bottom);
  left: 0;
  padding: 20rpx 60rpx;
  display: flex;
  justify-content: space-between;
  &::before{
    @include border(top, #DDD)
  }
  .delete-btn {
    border-radius: 40rpx;
    width: 80rpx;
    height: 80rpx;
    position: relative;
    &::before{
      @include border(full, #CACACA, 40rpx)
    }
  }
}
.nocheck-image {
  height: 50rpx;
  width: 50rpx;
}
.submitOrder {
  width: 480rpx;
  height: 80rpx;
  background: #F0831E;
  border-radius: 1000rpx;
  color: #ffffff;
  line-height: 80rpx;
  font-size: 32rpx;
}
.popup-tip-box {
  text-align: center;
  font-size: 30rpx;
  color: #414141;
  flex: 1;
  .btn{
    position: relative;
    width: 250rpx;
    height: 74rpx;
    margin: 80rpx auto 0 auto;
    background: #F7B064;
    color: #000;
    line-height: 72rpx;
    border-radius: 1000px;
    &::before{
      @include border(full, #414141, 1000px)
    }
  }
}
.ope-title {
  height: 90rpx;
  background: #f2f2f2;
  line-height: 90rpx;
  text-align: center;
  display: flex;
  justify-content: space-between;
  .box {
    width: 120rpx;
    font-size: 30rpx;
    color: #333333;
    font-weight: 500;
  }
}
</style>
